package com.loadmore.oneday.adapter

import android.content.Context
import android.graphics.Paint
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import com.loadmore.common.base.BaseAdapter
import com.loadmore.common.base.RVBaseHolder
import com.loadmore.common.constants.Api
import com.loadmore.common.model.BaseResponse
import com.loadmore.common.model.Task
import com.loadmore.common.net.Request
import com.loadmore.common.net.impl.JsonCallback
import com.loadmore.common.variables.Variables
import com.loadmore.oneday.R
import com.lzy.okgo.model.Response

/**
 *@author sunleilei
 *@date 2018/7/20
 *@time 11:00
 *
 */
class TaskListAdapter(context: Context) :BaseAdapter(context) {
    override fun getLayoutId(): Int {
        return R.layout.layout_task_list_item
    }

    override fun onBindViewHolder(holder: RVBaseHolder<*>, position: Int) {
        val task = getItem(position) as Task
        val title = holder.getText(R.id.task_name)
        val content = holder.getText(R.id.content)

        setStatus(false,task,task.status == 1,title,content)
        holder.setText(R.id.task_name,task.title).setText(R.id.content,task.content)
                .setCheck(R.id.toggle_status,task.status == 1)
        val check = holder.retrieve(R.id.toggle_status) as CheckBox
        check.setOnCheckedChangeListener { buttonView, isChecked ->
           setStatus(true,task,isChecked,title,content)
        }
    }

    private fun setStatus(click:Boolean,task:Task,isChecked:Boolean,title:TextView,content:TextView) {
        if (isChecked) {
            //update status to 1
//            title.isEnabled = false
//            content.isEnabled = false
            task.status = 1
            title.paintFlags =title.paintFlags.or(Paint.STRIKE_THRU_TEXT_FLAG)
            content.paintFlags = content.paintFlags.or(Paint.STRIKE_THRU_TEXT_FLAG)
        }else{
            //update status to 0
//            title.isEnabled = true
//            content.isEnabled = true
            task.status = 0
            title.paintFlags =title.paintFlags.and(Paint.STRIKE_THRU_TEXT_FLAG.inv())
            content.paintFlags =title.paintFlags.and(Paint.STRIKE_THRU_TEXT_FLAG.inv())
        }
        if (click) {
            updateTask(task.status,task.id)
        }
    }


    private fun updateTask(status:Int,task_id:Long) {
        Request.post(Api.update_task, hashMapOf<String,Any>("token" to Variables.token!!,
                "status" to status.toString(),"task_id" to task_id.toString()),
                object :JsonCallback<BaseResponse<Task>>() {
            override fun onSuccess(response: Response<BaseResponse<Task>>?) {
                if (status == 1) {
                    Toast.makeText(context,"完成了一项任务",Toast.LENGTH_SHORT).show()
                }
            }

        })
    }
}